const fs = require('fs');
const readline = require('readline');
const Carousel = require('./Carousel.js');
const configManager = require('./config.js');
let filePath = 'test/data.log';
// 检查命令行参数
if (process.argv.length > 3) {
    filePath = process.argv[2];
}

// 加载配置
async function loadConfig() {
    try {
        const config = await configManager.loadConfig();
        configManager.validateConfig(config);
        return config;
    } catch (error) {
        console.error("Failed to load configuration:", error.message);
        process.exit(1); // 直接退出程序
    }
}

// 创建Carousel实例
let carousel;
loadConfig().then(config => {
    carousel = new Carousel(config);
}).catch(error => {
    console.error('Failed to initialize Carousel:', error);
    process.exit(1);
});

// 创建文件读取流
const fileStream = fs.createReadStream(filePath, { encoding: 'utf8' });

// 创建readline接口
const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
});

// 添加对象转Map的辅助函数
function objectToMap(obj) {
    return new Map(Object.entries(obj));
}

// 处理每一行数据
rl.on('line', (line) => {
    console.log('LOG:', line);
    try {
        // 解析JSON数据
        if (line.startsWith('{')) {
            const data = JSON.parse(line);
            if (data.pointer) {
                carousel.pointer = data.pointer - 1;
                const result = carousel.newPointer(data);
            } 
            if (data.Labels) {
                carousel.rfid.labels = objectToMap(data.Labels);
            }
        }
    } catch (error) {
        console.error('处理数据时出错:', error.message);
        console.error('错误行:', line);
    }
});

// 处理文件读取完成
rl.on('close', () => {
    console.log('文件处理完成');
});

// 处理错误
rl.on('error', (error) => {
    console.error('读取文件时出错:', error);
});

fileStream.on('error', (error) => {
    console.error('打开文件时出错:', error);
    process.exit(1);
});